package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        SearchRequest searchRequest = getSearchRequest(params);

        // 分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        searchRequest.source().from((page - 1) * size).size(size);

        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            return getPageResult(searchResponse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static SearchRequest getSearchRequest(RequestParams params) {
        SearchRequest searchRequest = new SearchRequest("hotel");

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 关键词
        String key = params.getKey();
        if (StringUtils.isBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        // 城市
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }

        // 星级
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }

        // 品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }

        // 价格
        Integer maxPrice = params.getMaxPrice();
        Integer minPrice = params.getMinPrice();
        if (maxPrice != null && minPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        // 广告
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10))
                });

        searchRequest.source().query(functionScoreQueryBuilder);

        // 位置排序
        String location = params.getLocation();
        if (StringUtils.isNotBlank(location)) {
            searchRequest.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                                  .order(SortOrder.ASC)
                                  .unit(DistanceUnit.KILOMETERS)
            );
        }
        return searchRequest;
    }

    private PageResult getPageResult(SearchResponse searchResponse) {
        PageResult pageResult = new PageResult();

        long total = searchResponse.getHits().getTotalHits().value;
        pageResult.setTotal(total);

        SearchHit[] hits = searchResponse.getHits().getHits();
        List<HotelDoc> list = new ArrayList<>();
        if (hits != null && hits.length > 0) {
            for (SearchHit hit : hits) {
                String source = hit.getSourceAsString();
                HotelDoc hotelDoc = JSON.parseObject(source, HotelDoc.class);
                list.add(hotelDoc);

                Object[] sortValues = hit.getSortValues();
                if (sortValues != null && sortValues.length > 0) {
                    Object distance = sortValues[0];
                    hotelDoc.setDistance(distance);
                }
            }
        }
        pageResult.setHotels(list);

        return pageResult;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        SearchRequest searchRequest = getSearchRequest(params);

        // 分页
        searchRequest.source().size(0);
        searchRequest.source().aggregation(AggregationBuilders
                .terms("cityAggs")
                .field("city")
                .size(10));

        searchRequest.source().aggregation(AggregationBuilders
                .terms("starNameAggs")
                .field("starName")
                .size(10));

        searchRequest.source().aggregation(AggregationBuilders
                .terms("brandAggs")
                .field("brand")
                .size(10));

        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            Aggregations aggregations = searchResponse.getAggregations();

            Map<String, List<String>> result = new HashMap<>();

            Terms cityTerms = aggregations.get("cityAggs");
            List<String> cityList = cityTerms.getBuckets().stream().map(x -> x.getKeyAsString()).collect(Collectors.toList());
            result.put("city", cityList);

            Terms starNameTerms = aggregations.get("starNameAggs");
            List<String> starNameList = starNameTerms.getBuckets().stream().map(x -> x.getKeyAsString()).collect(Collectors.toList());
            result.put("starName", starNameList);

            Terms brandTerms = aggregations.get("brandAggs");
            List<String> brandList = brandTerms.getBuckets().stream().map(x -> x.getKeyAsString()).collect(Collectors.toList());
            result.put("brand", brandList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateEsDoc(Long id) {
        Hotel hotel = this.getById(id);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        String json = JSON.toJSONString(hotelDoc);

        IndexRequest indexRequest = new IndexRequest("hotel");
        indexRequest.source(json, XContentType.JSON).id(id.toString());

        try {
            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
            log.info("[更新es文档]{}，结果{}", id, indexResponse.getResult().getLowercase());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteEsDoc(Long id) {
        DeleteRequest deleteRequest = new DeleteRequest("hotel", id.toString());
        try {
            DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
            log.info("[删除es文档]{}，结果{}", id, deleteResponse.getResult().getLowercase());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
